using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet;
using MQTTnet.Client.Options;
using MQTTnet.Client.Receiving;
using System.Text;
using MQTTnet.Client;
using MQTTnet.Protocol;
using System.Diagnostics;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace Panty.Test
{
    public interface IMqttclinetModel : IModule
    {
        IMqttClient mqttClient { get; set; }
        void CreatClient(string ClinetID, string IP, int port, string[] Topic);
        void SendMessage(string topic, string message);
    }
    public class MqttclinetModel : AbsModule, IMqttclinetModel
    {

        public  IMqttClient mqttClient { get; set; }
        protected override void OnInit()
        {

        } 

        async void IMqttclinetModel.CreatClient(string ClinetID, string IP, int port, string[] Topic)
        {
            // 创建MQTT客户端选项
            var mqttClientOptions = new MqttClientOptionsBuilder()
                .WithClientId(ClinetID) // 设置客户端ID
                .WithTcpServer(IP, port) // 设置服务器地址和端口
                .WithCleanSession()
                .Build();

            // 创建MQTT客户端
            mqttClient = new MqttFactory().CreateMqttClient();

            // 处理连接事件
            mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e =>
            {

                // 订阅主题
                foreach (var mqtt in Topic)
                {
                    mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(mqtt).Build()).Wait();
                }
            });

            // 处理断开连接事件
            mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(e =>
            {
                Debug.Log($"与服务端断开连接");
            });

            // 处理消息接收事件
            mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                var message = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                Debug.Log($"收到主题:{e.ApplicationMessage.Topic} 消息:{message}");

            });

            // 连接到MQTT服务器
            await mqttClient.ConnectAsync(mqttClientOptions);
        }

        async void IMqttclinetModel.SendMessage(string topic, string message)
        {
            // 创建MQTT消息
            var mqttMessage = new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload(message)
                .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
                .Build();

            // 发布消息
            await mqttClient.PublishAsync(mqttMessage);
        }

        
    }
}